//
//  LoginViewController.m
//  HaiKangDemo
//
//  Created by 崔 on 16/10/3.
//  Copyright © 2016年 崔. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginTextField.h"
#import "LGControllerManager.h"
#import "LGtools.h"
#import "TouchIDManager.h"
#import "ALSHeader.h"
#import "GlobalKit.h"
#import "SVProgressHUD.h"
#import "LoginWindow.h"


#define k_loginWindow [LoginWindow shareLoginWindw]
#define CHYCAMERALISTPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"cameraList.plist"]

@interface LoginViewController ()<UITextFieldDelegate,SettingNewPasswordDelegate>

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UILabel *presentationLab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *logoTop;
@property (weak, nonatomic) IBOutlet UIButton *touchIDLoginBtn;

@property (strong, nonatomic) NSString *password;
@property (strong, nonatomic) TouchIDManager *IDManager;
@end

@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupchildView];
    [self setupNotification];
    self.touchIDLoginBtn.hidden = YES;
//    self.touchIDLoginBtn.highlighted = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//#warning 删除代码
//    [self loginSuccess];
//    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:ALSAdministrators];
//    return;

    if ([[NSUserDefaults standardUserDefaults]boolForKey:ALSStartTouchID] == NO) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:ALSStartTouchID];
        self.touchIDLoginBtn.hidden = !self.IDManager.canUseTouchID;
        return;
    }
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:ALSTouchIDLogin]) {
        [self touchIDLoginBtnClick:nil];
    }else {
        self.touchIDLoginBtn.hidden = !self.IDManager.canUseTouchID;
    }

}

- (void)setupchildView {
    self.passwordTextField.delegate = self;
    self.passwordTextField.tintColor = kColorFromRGB(0x3fedeb);
    self.presentationLab.hidden = YES;
}

- (void)setupNotification {
    //  如果屏幕高度大于480，不处理。
    if (kScreen_H > 480) {
        return;
    }
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)keyboardWillHide {
    
    self.logoTop.constant = 120;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    }];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    self.logoTop.constant = 0;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view layoutIfNeeded];
    }];
    
}

- (IBAction)touchIDLoginBtnClick:(UIButton *)sender {
    
    NSError *error;
    BOOL use = [self.IDManager canUseTouchIDWithError:&error];
    if (use) {
        [k_loginWindow showTouchIDLoadingHUD];
    }else {
        switch (error.code) {
            case LAErrorTouchIDLockout:
                [k_loginWindow showTouchIDLockHUD];
                break;
            default:
                
                break;
        }
        return;
    }
    
    __weak LoginViewController *weakSelf = self;
    
    [self.IDManager touchIDLoginSuccessHandler:^{
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:ALSAdministrators];
        [weakSelf loginSuccess];
        
    } failHandler:^(NSError * _Nullable error) {
        NSLog(@"%@",error.localizedDescription);
        switch (error.code) {
            case LAErrorTouchIDLockout:
                //指纹被锁定
                [k_loginWindow showTouchIDLockHUD];
                break;
            case LAErrorAuthenticationFailed:
                //3次验证指纹失败
                [k_loginWindow showTouchIDAuthenticationFailedHUD];
                break;
            default:
                break;
        }
    }];
    
}

//登录
- (IBAction)login {
    [self.view endEditing:YES];
    if ([self checkingPassword]) {
        [self loginSuccess];
    }
}
//检查密码正确性
- (BOOL)checkingPassword {
    //密码为空
    if (self.passwordTextField.text.length == 0) {
        self.presentationLab.text = @"密码不能为空";
        self.presentationLab.hidden = NO;
        return NO;
    }
    //密码正确 - 超级管理员
    if ([ALSSupervisorPassword isEqualToString:self.passwordTextField.text]) {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:ALSAdministrators];
        self.presentationLab.hidden = YES;
        return YES;
    }
    
    //密码正确 - 普通密码
    if ([self.password isEqualToString:self.passwordTextField.text]) {
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:ALSAdministrators];
        self.presentationLab.hidden = YES;
        return YES;
    }
    //密码不为空 错误
    self.presentationLab.text = @"密码错误";
    self.presentationLab.hidden = NO;
    return NO;
}
//登陆成功 跳转
- (void)loginSuccess {
//    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:ALSLoginState];
    [k_loginWindow dismiss];
    self.passwordTextField.text = nil;
}

- (IBAction)forgetPassword:(UIButton *)sender {
    
    //判断是否能使用指纹解锁
    __block NSError *error;
    __block BOOL canUseTouchID = [self.IDManager canUseTouchIDWithError:&error];
    
    NSString *alertMessage = @"您可以通过验证已有指纹，重设密码，或者联系管理员。";
    __weak LoginViewController *weakSelf = self;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *setNewPassword = [UIAlertAction actionWithTitle:@"设置新密码" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if (canUseTouchID) {
            [weakSelf performSegueWithIdentifier:@"settingnewpassword" sender:nil];
        }else {
            switch (error.code) {
                case LAErrorTouchIDLockout:
                    [k_loginWindow showTouchIDLockHUD];
                    break;
                default:
                    break;
            }
        }
    }];
    
    [alertController addAction:alertAction];
    [alertController addAction:setNewPassword];

    [self presentViewController:alertController animated:YES completion:nil];
}

//重置密码
- (void)reset {
    
    //重置密码

    [[NSUserDefaults standardUserDefaults]setObject:ALSDefaultPassword forKey:ALSPassword];
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    //注销海康服务器
    [[GlobalKit shareKit] clearSession];
    
    //移除所有 门禁控制器
    [[LGControllerManager shareControllerManager] removeAllItem];
    //删除cameraList.plist
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    
    if (![fileMgr removeItemAtPath:CHYCAMERALISTPath error:nil]) {
        NSLog(@"删除cameraList.plist失败！");
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    [super prepareForSegue:segue sender:sender];
    SettingNewPasswordViewController *settingNewPasswordVC = segue.destinationViewController;
    settingNewPasswordVC.Delegete = self;
}

#pragma mark - uitextfielddelegate
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [self checkingPassword];
    return YES;
}
#pragma mark - settingnewpassworddelegate
- (void)settingNewPasswordSuccess {
    [self loginSuccess];
}
#pragma mark - load

- (NSString *)password {
    _password = [[NSUserDefaults standardUserDefaults] objectForKey:ALSPassword];
    if (_password.length == 0) {
        _password = ALSDefaultPassword;
        [[NSUserDefaults standardUserDefaults]setObject:ALSDefaultPassword forKey:ALSPassword];
    }
    return _password;
}

- (TouchIDManager *)IDManager {
    return [TouchIDManager sharedTouchIDManager];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
